// AppInfo: '/managment/app/info', // 获取公众号信息
// RelatedPaper: '/managment/app/paper', // 关联问卷
// GetKeywords: '/managment/app/keywords', // 获取关键词
// PostKeywords: '/managment/app/keywords', // 修改关键词
// SetReply: '/managment/app/replyMsg', // 设置关注自动回复消息
// AppReplyMsg: '/managment/app/replyMsg', // 获取关注自动回复消息
import storage from 'store'
import { CURRENT_APP } from '@/store/mutation-types'


import {
    fetchAppInfo
} from '@/api/paper'

const apps = {
    state: {
        apps: [],
        currentApp: ''

    },

    mutations: {
        SET_APPS: (state, apps) => {
            state.apps = apps
        },
        SET_CURRENTAPP: (state, app) => {
            state.currentApp = app
        },
    },

    actions: {
        // 获取公众号信息
        FetchApp({ commit }) {
            return new Promise((resolve, reject) => {
                fetchAppInfo().then(response => {
                    commit('SET_APPS', response.data.apps)

                    // local 有记录选择的appid 先判断该appid是否还存在当前用户
                    let isAppid = false
                    response.data.apps.forEach(i => {
                        if (i.appid == storage.get(CURRENT_APP)) { isAppid = true }
                    })
                    if (storage.get(CURRENT_APP) && !isAppid) { storage.remove(CURRENT_APP) }

                    if (response.data.apps.length) {
                        commit('SET_CURRENTAPP', storage.get(CURRENT_APP) || response.data.apps[0].appid)
                        if (!storage.get(CURRENT_APP)) {
                            storage.set(CURRENT_APP, response.data.apps[0].appid)
                        }
                    }

                    resolve(response)
                }).catch(error => {
                    reject(error)
                })
            })
        },
        // 切换公众号
        SwitchApp({ commit }, app) {
            return new Promise(resolve => {
                storage.set(CURRENT_APP, app)
                commit('SET_CURRENTAPP', app)
                resolve({
                    code: 200
                })
            })
        }
    }
}

export default apps